// index.js
// 获取应用实例
const app = getApp()

Page({
  data: {
    books: [],
    imageURL: '../../../../assets/images/bookimg.png'
  },
  onShow() {
    console.log('调用后台API,查询所有上架的商品');
    // 获取所有商品信息
    this.getGoods()
  },
  // 调用后台API, 获取所有商品信息
  getGoods() {
    wx.cloud.callFunction({
      name: 'book_show',
      success: res => {
        console.log('后台book_show的响应信息：', res.result.data);
        let newBooks = res.result.data
        // 将后台的res中的_id改名为id
        newBooks = JSON.parse(JSON.stringify(newBooks).replace(/_id/g,"id"));
        newBooks = newBooks.map(book => {
          book.amount = `${book.amount}.00`
          return book
        })
        // console.log('newBooks = ', newBooks);
        this.setData({books: newBooks})
      }
    })
  },
  // 获取所点击商品的id，并跳转到详情页
  goDetail(e) {
    const goodid = e.currentTarget.dataset.id
    console.log(goodid);
    wx.navigateTo({
      url: `/pages/goods_detail/goods_detail?goodid=${goodid}`
    })
  },
  // 搜索商品，模糊匹配
  searchShelves(e) {
    wx.cloud.callFunction({
      name: 'book_search',
      data: {
        bookName: e.detail
      },
      success: res => {
        const books = res.result.data
        console.log('从book_search返回的信息：', books);
        this.setData({
          books
        })
      },
      fail: res => {
        console.log('从book_search返回的错误信息：', res);
      }
    })
  },
  // 取消搜索，清空搜索框
  cancelSearch(e) {
    console.log('取消搜索，调用后台API，以books结构，返回所有图书');
    e.detail = ''
    this.getGoods()
  }
})
